package v1

import (
	"fmt"
	"github.com/sirupsen/logrus"

	//"fmt"
	//"github.com/docker/docker/api/types"
	//"github.com/docker/docker/client"
	"github.com/gin-gonic/gin"
	"net/http"
	"test/tools"

	//"context"
)

// Gin 下载镜像，改名后，推送至 docker 官方仓库
// 已经存在镜像则返回已存在
func ImagePullFunc (c *gin.Context) {
	imagepullname := c.Query("imagepullname")

	// 查询镜像是否已经存在
	returcode, err := tools.CheckImagePull(imagepullname)

	if err != nil {
		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePullFunc",
		}).Warn(err)
		c.JSON(http.StatusBadRequest, gin.H{
			"status":  tools.ERROR_IMAGE_CHECK,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_CHECK),
		})
		return
	}
	if returcode == 1 {
		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePullFunc",
		}).Warn(tools.GetErrMsg(tools.ERROR_IMAGE_CHECK))

		c.JSON(http.StatusBadRequest, gin.H{
			"status":  tools.ERROR_IMAGE_CHECK,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_CHECK),
		})
		return
	}

	imagenamealise, err := tools.PullImage(imagepullname)

	if err != nil {
		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePullFunc",
		}).Warn(tools.GetErrMsg(tools.ERROR_IMAGE_PULL))

		c.JSON(http.StatusBadRequest, gin.H{
			"status":  tools.ERROR_IMAGE_PULL,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_PULL),
		})

		return
	}

	// 成功
	// 镜像进行别名操作
	err = tools.ImageTag(imagepullname, imagenamealise)
	if err != nil {
		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePullFunc",
		}).Warn(tools.GetErrMsg(tools.ERROR_IMAGE_TAG))

		c.JSON(http.StatusBadRequest, gin.H{
			"status": tools.ERROR_IMAGE_TAG,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_TAG),
		})

		return
	}

	// 将镜像推送至 docker 官方仓库
	err = tools.PushImage(imagenamealise)
	if err != nil {
		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePullFunc",
		}).Warn(tools.GetErrMsg(tools.ERROR_IMAGE_PUSH))

		c.JSON(http.StatusBadRequest, gin.H{
			"status": tools.ERROR_IMAGE_PUSH,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_PUSH),
		})
		return
	}

	c.JSON(http.StatusOK, gin.H{
		"status":  tools.SUCCSE,
		"message": tools.GetErrMsg(tools.SUCCSE),
		"imagename": imagenamealise,
	})
}



// Gin 推送镜像，如果出现镜像为正常写入，可以手动利用当前接口进行镜像推送
func ImagePushFunc(c *gin.Context) {
	// 查询 imagepushname
	imagepushname := c.Query("imagepushname")

	// 镜像镜像名是否在数据库中存在
	returcode, err := tools.CheckImagePush(imagepushname)

	// 检测名称失败
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": tools.ERROR_IMAGE_ALWAYS_EXIT_PUSH,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_ALWAYS_EXIT_PUSH),
		})

		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePushFunc",
		}).Error(fmt.Sprintf("检测镜像名称失败：%v", imagepushname))
		return
	}

	// 检测镜像名称不存在，无法推送
	if returcode != 1 {
		c.JSON(http.StatusBadRequest, gin.H{
			"status":  tools.ERROR_IMAGE_NOT_EXIT,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_NOT_EXIT),
		})

		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePushFunc",
		}).Error(fmt.Sprintf("检测镜像不存在：%v", imagepushname))

		return
	}

	// 推送镜像
	err = tools.PushImage(imagepushname)
	// 镜像推送失败
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": tools.ERROR_IMAGE_PUSH_ONCE,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_PUSH_ONCE),
		})

		tools.Log.WithFields(logrus.Fields{
			"msg": "ImagePushFunc",
		}).Error(fmt.Sprintf("推送镜像失败：%v", imagepushname))
		return
	}

	// 完全推送成功
	c.JSON(http.StatusOK, gin.H{
		"status":  tools.SUCCSE,
		"message": tools.GetErrMsg(tools.SUCCSE),
	})

	tools.Log.WithFields(logrus.Fields{
		"msg": "ImagePushFunc",
	}).Info(fmt.Sprintf("镜像推送成功：%v", imagepushname))

}

// Gin 通过镜像原名返回镜像别名
func ImageQueryFunc(c *gin.Context) {
	imagecheck := c.Query("imagecheck")
	returnName, err := tools.CheckImageName(imagecheck)

	// 判断查询请求是否成功，如果失败返回
	if err != nil {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": tools.ERROR_IMAGE_QUERY,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_QUERY),
		})

		tools.Log.WithFields(logrus.Fields{
			"msg": "ImageQueryFunc",
		}).Error(fmt.Sprintf("执行检测函数失败：%v", imagecheck))
		c.Abort()
		return
	}

	// 判断查询结果是否为空，为空则表示没有对应的镜像存在
	if returnName == ""{
		c.JSON(http.StatusBadRequest, gin.H{
			"status": tools.ERROR_IMAGE_QUERY_RETURN,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_QUERY_RETURN),
		})

		tools.Log.WithFields(logrus.Fields{
			"msg": "ImageQueryFunc",
		}).Error(fmt.Sprintf("检测镜像结果为空：%v", imagecheck))
		c.Abort()
		return
	}

	// 存在转换的镜像结果，返回即可
	c.JSON(http.StatusOK, gin.H{
		"status":  tools.SUCCSE,
		"message": tools.GetErrMsg(tools.SUCCSE),
		"returnname": returnName,
	})

	tools.Log.WithFields(logrus.Fields{
		"msg": "ImageQueryFunc",
	}).Info(fmt.Sprintf("执行检测函数成功：%v", imagecheck))
}


// Gin 列出当前拥有的镜像，改名前
func ImageListFunc(c *gin.Context) {
	imageTypeSlice := tools.ListImageDb()

	var gh gin.H = gin.H{
		"status": tools.SUCCSE,
	}


	if len(imageTypeSlice) == 0 {
		c.JSON(http.StatusBadRequest, gin.H{
			"status": tools.ERROR_IMAGE_QUERY_LIST,
			"message": tools.GetErrMsg(tools.ERROR_IMAGE_QUERY_LIST),
		})

		tools.Log.WithFields(logrus.Fields{
			"msg": "ImageListFunc",
		}).Error(fmt.Sprintf("查询镜像列表为空"))
		c.Abort()
		return
	}

	// 循环遍历将镜像名写入至返回的 json 响应体
	for _, values := range imageTypeSlice {
		gh[fmt.Sprintf("%v", values.ImageName)] = values.ImageAlias

		// 查询的镜像名或者别名为空
		if values.ImageAlias == "" || values.ImageName == ""{
			c.JSON(http.StatusBadRequest, gin.H{
				"status": tools.ERROR_IMAGE_QUERY_LIST,
				"message": tools.GetErrMsg(tools.ERROR_IMAGE_QUERY_LIST),
			})

			tools.Log.WithFields(logrus.Fields{
				"msg": "ImageListFunc",
			}).Error(fmt.Sprintf("查询的数据镜像名或者镜像别名数据为空"))
			c.Abort()
			return
		}
	}

	c.JSON(http.StatusOK, gh)

	tools.Log.WithFields(logrus.Fields{
		"msg": "ImageListFunc",
	}).Info(fmt.Sprintf("镜像列表查询成功"))
}


func HelpPrintFunc(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"View a list of wall flipped mirrors": "curl --location --request GET  'http://localhost:8080/api/v1/imagelist' --header 'User-Agent: Apipost client Runtime/+https://www.apipost.cn/'",
		"Download images that need to be downloaded over the wall": "curl --location  --request POST  'http://localhost:8080/api/v1/imagepull?imagepullname=ImageName' --header 'User-Agent: Apipost client Runtime/+https://www.apipost.cn/' --header 'Content-Type: application/json' --data ''",
		"Query the domestic download address of the image": "curl --location --request GET 'http://localhost:8080/api/v1/imagequery?imagecheck=ImageName' --header 'User-Agent: Apipost client Runtime/+https://www.apipost.cn/'",
	})

	tools.Log.WithFields(logrus.Fields{
		"msg": "HelpPrintFunc",
	}).Error(fmt.Sprintf("打印帮助信息成功"))
}